<template>
  <div class="select-input-container">
    <el-input
      :model-value="props.value"
      placeholder="请选择口味"
      readonly
      @focus="isDropdownVisible = true"
      @blur="handleBlur"
    />
    <div v-if="isDropdownVisible && availableFlavors.length" class="flavor-dropdown">
      <span
        v-for="item in availableFlavors"
        :key="item.name"
        class="flavor-item"
        @mousedown.prevent="handleSelect(item)"
      >
        {{ item.name }}
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import type { PropType } from 'vue';

const props = defineProps({
  value: String,
  availableFlavors: {
    type: Array as PropType<{ name: string; value: string[] }[]>,
    default: () => []
  }
});

const emit = defineEmits(['select']);

const isDropdownVisible = ref(false);

const handleBlur = () => {
  // 延迟关闭，以便 handleSelect 事件能被触发
  setTimeout(() => { isDropdownVisible.value = false; }, 200);
};

const handleSelect = (flavor: { name: string; value: string[] }) => {
  emit('select', flavor);
  isDropdownVisible.value = false;
};
</script>

<style lang="scss" scoped>
.select-input-container {
  position: relative;
  width: 100%;
}
.flavor-dropdown {
  position: absolute;
  top: 42px;
  left: 0;
  width: 100%;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
  padding: 5px 0;
  .flavor-item {
    display: block;
    padding: 0 20px;
    line-height: 34px;
    cursor: pointer;
    &:hover {
      background-color: #f5f7fa;
    }
  }
}
</style>
